<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Crm\Controller;

use PHPExcel;
use PHPExcel_Worksheet;
use PHPExcel_IOFactory;
use Zend\View\Model\ViewModel;
use Crm\Common\CommonHelper;
use Crm\Lib\WxPayApi;
use Crm\Lib\WxPayConfig;
use Crm\Lib\WxPayRefund;
use Crm\View\Helper\CommonHelper as viewComHelper;

class OrderController extends AbstractController
{
    /*
     * 订单列表
     */
    public function indexAction()
    {
        $cityList = array();
        $cityList = $this->getCityTable()->find();
        $catalogList = array();
        $catalogList = $this->getCatalogTable()->find();
        $organizationList = array();
        $organizationList = $this->getOrganizationTable()->findAll();
        return new ViewModel(array(
            'city'=>$cityList,
            'catalog'=>$catalogList,
            'organization'=>$organizationList,
        ));
    }
    
    /*
     * 订单列表
     */
    public function ajaxOrderListTableAction()
    {
        
        $post = $this->request->getPost()->toArray();
        
        $paginator = $this->getOrderTable()->getOrderList($post);
        $result = array(
            'paginator' => $paginator,
        );
        
        $viewModel = new ViewModel();
        $viewModel->setVariables($result)
              ->setTerminal(true);

        return $viewModel;
    }
    
    /*
     * 订单详情
     */
    public function orderDetailAction()
    {
        $params=$this->getEvent()->getRouteMatch()->getParams();
        $order_id=$params['id']?$params['id']:0;
        $order = $this->getOrderTable()->getByOrderId($order_id);
        $orderItem = $this->getOrderitemTable()->getOrderitemList(array('order_id'=>$order_id));
        return new ViewModel(array(
            'order' => $order,
            'orderItem' => $orderItem,
        ));
    }
    /*
     * 订单评价
     */
    public function scoreAction()
    {
        $params=$this->getEvent()->getRouteMatch()->getParams();
        $order_id=$params['id']?$params['id']:0;
        $score = $this->getOrderScoreTable()->findOne($order_id);
        if(count($score)>0){
            $scoreItem = $score[0];
        }else{
            $scoreItem = array(
                'order_no'=>'',
                'user_name'=>'',
                'clear_score'=>'',
                'taste_score'=>'',
                'speed_score'=>'',
                'service_score'=>'',
                'total_score'=>'',
            );
        }
//         var_dump($score);
//         die();
        return new ViewModel(array(
            'score' => $scoreItem,
        ));
    }
    public function saveOrderAction()
    {
        $orderTable = $this->getOrderTable();
        $data = $this->request->getPost()->toArray();
        $order=array(
            'status'=>$data['status'],
            'address_info'=>$data['address_info'],
            'receiver_name'=>$data['receiver_name'],
            'cellphone'=>$data['cellphone'],
            //'user_id'=>$data['user_id'],
            'receiver_mark'=>$data['receiver_mark'],
            'send_time'=>$data['send_time'],
            'order_mark'=>$data['order_mark'],
            'express_no'=>$data['express_no'],
            'express_name'=>$data['express_name'],
        );
        try{
            $orderTable->updateItem($data['order_id'],$order);
        
            $this->flashMessenger()->addSuccessMessage("保存成功！");
            return $this->redirect()->toRoute('crm/order');
        }catch(\Exception $e)
        {
            //die($e);
            $this->flashMessenger()->addErrorMessage("保存失败！");
            return $this->redirect()->toRoute('crm/order',array('action'=>'order-detail','id'=>$data['order_id']));
        }
    }
    public function excelOrderAction()
    {
        $query = $this->request->getQuery()->toArray();
        $outExcelList = array();
        $outExcelList = $this->getOrderTable()->getOutExcelList($query);
    
        $objPHPExcel = new PHPExcel();
        //sheet1 订单列表
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '订单NO')
        ->setCellValue('B1', '商户ID')
        ->setCellValue('C1', '商户名称')
        ->setCellValue('D1', '用户ID')
        ->setCellValue('E1', '用户名称')
        ->setCellValue('F1', '订单总价')
        ->setCellValue('G1', '订单时间')
        ->setCellValue('H1', '订单状态')
        ->setCellValue('I1', '收货人')
        ->setCellValue('J1', '电话')
        ->setCellValue('K1', '收货人备注')
        ->setCellValue('L1', '订单备注');
        $viewComHelper = new viewComHelper();
        //详细数据
        foreach ($outExcelList as $key=>$order){
            $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A'.($key + 2), $order['order_no'])
            ->setCellValue('B'.($key + 2), $order['org_id'])
            ->setCellValue('C'.($key + 2), $order['org_name'])
            ->setCellValue('D'.($key + 2), $order['user_id'])
            ->setCellValue('E'.($key + 2), $order['user_name'])
            ->setCellValue('F'.($key + 2), $order['order_total_price'])
            ->setCellValue('G'.($key + 2), $order['order_create_time'])
            ->setCellValue('H'.($key + 2), $viewComHelper->orderStatus($order['status']))
            ->setCellValue('I'.($key + 2), $order['receiver_name'])
            ->setCellValue('J'.($key + 2), $order['cellphone'])
            ->setCellValue('K'.($key + 2), $order['receiver_mark'])
            ->setCellValue('L'.($key + 2), $order['order_mark']);
        }
    
        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('订单列表');
        
        //sheet2 订单商品明细
        $pSheet = new PHPExcel_Worksheet($objPHPExcel,'订单商品明细');
        $outProDetailList = array();
        $outProDetailList = $this->getOrderTable()->getOutExcelDetailList($query);
        $pSheet
        ->setCellValue('A1', '订单NO')
        ->setCellValue('B1', '商品ID')
        ->setCellValue('C1', '商品名称')
        ->setCellValue('D1', '商品价格')
        ->setCellValue('E1', '数量')
        ->setCellValue('F1', '配餐日期')
        ->setCellValue('G1', '配餐时段');
         $viewComHelper = new viewComHelper();
        //详细数据
        foreach ($outProDetailList as $key=>$order){
            $pSheet
            ->setCellValue('A'.($key + 2), $order['order_no'])
            ->setCellValue('B'.($key + 2), $order['product_id'])
            ->setCellValue('C'.($key + 2), $order['oi_name'])
            ->setCellValue('D'.($key + 2), $order['oi_price'])
            ->setCellValue('E'.($key + 2), $order['oi_amount'])
            ->setCellValue('F'.($key + 2), $order['oi_meal_send_time'])
            ->setCellValue('G'.($key + 2), $viewComHelper->mealType($order['oi_meal_type']));
        }
        // Rename worksheet
        $objPHPExcel->addSheet($pSheet);
        
        //sheet3 销售商品统计
        $pSheet3 = new PHPExcel_Worksheet($objPHPExcel,'商品统计');
        $outProProList = array();
        $outProProList = $this->getOrderTable()->getOutExcelProList($query);
        $pSheet3
        ->setCellValue('A1', '配餐日期')
        ->setCellValue('B1', '配餐时段')
        ->setCellValue('C1', '商品ID')
        ->setCellValue('D1', '商品名称')
        ->setCellValue('E1', '配送数量');
         $viewComHelper = new viewComHelper();
        //详细数据
        foreach ($outProProList as $key=>$order){
            $pSheet3
            ->setCellValue('A'.($key + 2), $order['oi_meal_send_time'])
            ->setCellValue('B'.($key + 2), $viewComHelper->mealType($order['oi_meal_type']))
            ->setCellValue('C'.($key + 2), $order['product_id'])
            ->setCellValue('D'.($key + 2), $order['oi_name'])
            ->setCellValue('E'.($key + 2), $order['count']);
        }
        // Rename worksheet
        $objPHPExcel->addSheet($pSheet3);
        
        
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); // 生成excel文件 Excel2007
        CommonHelper::browserExport('Excel5', '订单_'.date('YmdHis').'.xls'); // 输出到浏览器
        $objWriter->save("php://output");
        exit();
    }
    
    
    /*
     * 退货申请
     */
    public function returnAction()
    {
        return new ViewModel();
    }
    
    /*
     * 退货列表
     */
    public function ajaxReturnTableAction()
    {
    
        $post = $this->request->getPost()->toArray();
    
        $paginator = $this->getReturnOrderTable()->getReturnOrderList($post);
        $result = array(
            'paginator' => $paginator,
        );
    
        $viewModel = new ViewModel();
        $viewModel->setVariables($result)
        ->setTerminal(true);
    
        return $viewModel;
    }
    /*
     * 同意退货
     */
    public function agreeReturnAction()
    {
        $request = $this->getRequest();
        $order_id = $request->getPost('order_id');

        try{
            $this->getReturnOrderTable()->updateStatus($order_id);
            $response=array(
                'result' => 'true',
                'reason' => '处理成功！',
            );
            die(json_encode($response));
        }catch (\Exception $e){
            $response=array(
                'result' => 'false',
                'reason' => '处理失败！',
            );
            die(json_encode($response));
        }
    }
    
    /*
     * 发货
     */
    public function sendOrderAction()
    {
    
        $request = $this->getRequest();
        $order_id = $request->getPost('order_id');
        $order_type = $request->getPost('order_type');
        $express_no = $request->getPost('express_no');
        $express_name = $request->getPost('express_name');
        
        $order = $this->getOrderTable()->getByOrderId($order_id);
        if(!$order || $order['status'] != '2'){
            $response=array(
                'result' => 'false',
                'reason' => '发货失败，请选择待发货订单！',
            );
            die(json_encode($response));
        }
        
        
        try{
            $orderTable = $this->getOrderTable();
            if($order_type == '2'){
                $orderTable->sendOrder($order_id,array('express_no'=>$express_no,'express_name'=>$express_name));
            }else{
                $orderTable->sendOrder($order_id,array());
            }
            $response=array(
                'result' => 'true',
                'reason' => '发货成功！',
            );
            die(json_encode($response));
        }catch (\Exception $e){
            $response=array(
                'result' => 'false',
                'reason' => '发货失败！',
            );
            die(json_encode($response));
        }
    }
    
    /*
     * 退款
     */
    public function refundMoneyAction()
    {
        $request = $this->getRequest();
        $order_id = $request->getPost('order_id');
        $refund_price = $request->getPost('refund_price');
        
        try{
            $order = $this->getOrderTable()->getByOrderId($order_id);
            if(!$order){
                $response=array(
                    'result' => 'false',
                    'reason' => '无效订单！',
                );
                die(json_encode($response));
            }
            
            $input = new WxPayRefund();
            $input->SetOut_trade_no($order['order_no']);
            $input->SetTotal_fee($order['order_total_price']*100);
            $input->SetRefund_fee($refund_price*100);
            $input->SetOut_refund_no($order['order_no'].'_'.date("YmdHis"));
            $input->SetOp_user_id(WxPayConfig::MCHID);
            $resultData = WxPayApi::refund($input);
            $refundLog = array(
                'order_refund_id'=>$order['order_no'].'_'.date("YmdHis"),
                'order_id'=>$order_id,
                'order_no'=>$order['order_no'],
                'org_id'=>$order['org_id'],
                'return_code'=>$resultData['return_code'],
                'return_msg'=>isset($resultData['return_msg'])?$resultData['return_msg']:'',
                'crm_user_id'=>$_SESSION['account']['user_id'],
                'order_total_price'=>$order['order_total_price'],
                'refund_fee'=>$refund_price,
                'type'=>1,
                'result_code'=>$resultData['result_code'],
                'err_code'=>isset($resultData['err_code'])?$resultData['err_code']:'',
                'err_code_des'=>isset($resultData['err_code_des'])?$resultData['err_code_des']:'',
            );
            $this->getRefundFeeLogTable()->addItem($refundLog);
            
            if($resultData['return_code'] == 'SUCCESS' && $resultData['result_code'] == 'SUCCESS'){
                $response=array(
                    'result' => 'true',
                    'reason' => '退款成功！',
                );
                die(json_encode($response));
            }else{
                $response=array(
                    'result' => 'false',
                    'reason' => '微信接口异常,退款失败！',
                );
                die(json_encode($response));
            }
        }catch (\Exception $e){
            $response=array(
                'result' => 'false',
                'reason' => '系统异常,退款失败！',
            );
            die(json_encode($response));
        }
        
    }
    
    /*
     * 取消订单申请
     */
    public function cancelAction()
    {
        return new ViewModel();
    }
    
    /*
     * 取消订单列表
     */
    public function ajaxCancelTableAction()
    {
    
        $post = $this->request->getPost()->toArray();
    
        $paginator = $this->getOrderTable()->getCancelOrderList($post);
        $result = array(
            'paginator' => $paginator,
        );
    
        $viewModel = new ViewModel();
        $viewModel->setVariables($result)
        ->setTerminal(true);
    
        return $viewModel;
    }
    /*
     * 同意取消订单
     */
    public function agreeCancelAction()
    {
        $request = $this->getRequest();
        $order_id = $request->getPost('order_id');
    
        try{
            $this->getOrderTable()->beginTransaction();
            //退款
            $order = $this->getOrderTable()->getByOrderId($order_id);
            if(!$order){
                $response=array(
                    'result' => 'false',
                    'reason' => '无效订单！',
                );
                $this->getOrderTable()->rollBack();
                die(json_encode($response));
            }
            if($order['trade_channel'] == 'balance'){
                $userInfo = $this->getUserTable()->findOne($order['user_id']);
                $this->getUserTable()->updateBalance($order['user_id'],$order['order_total_price'] + $userInfo['balance']);
                $this->getUserBalanceLogTable()->create(array(
                    'user_id'=>$order['user_id'],
                    'ubl_income'=>$order['order_total_price'],
                    'ubl_balance'=>$order['order_total_price'] + $userInfo['balance'],
                    'ubl_remark'=>'取消订单退款',
                    'ubl_detail'=>'取消订单退款',
                ));
            }elseif($order['trade_channel'] == 'wx') {
                $input = new WxPayRefund();
                $input->SetOut_trade_no($order['order_no']);
                $input->SetTotal_fee($order['order_total_price']*100);
                $input->SetRefund_fee($order['order_total_price']*100);
                $input->SetOut_refund_no($order['order_no'].'_'.date("YmdHis"));
                $input->SetOp_user_id(WxPayConfig::MCHID);
                $resultData = WxPayApi::refund($input);
                $refundLog = array(
                    'order_refund_id'=>$order['order_no'].'_'.date("YmdHis"),
                    'order_id'=>$order_id,
                    'order_no'=>$order['order_no'],
                    'org_id'=>$order['org_id'],
                    'return_code'=>$resultData['return_code'],
                    'return_msg'=>isset($resultData['return_msg'])?$resultData['return_msg']:'',
                    'crm_user_id'=>$_SESSION['account']['user_id'],
                    'order_total_price'=>$order['order_total_price'],
                    'refund_fee'=>$order['order_total_price'],
                    'type'=>1,
                    'result_code'=>$resultData['result_code'],
                    'err_code'=>isset($resultData['err_code'])?$resultData['err_code']:'',
                    'err_code_des'=>isset($resultData['err_code_des'])?$resultData['err_code_des']:'',
                );
                $this->getRefundFeeLogTable()->addItem($refundLog);
                
                if($resultData['return_code'] != 'SUCCESS' || $resultData['result_code'] != 'SUCCESS'){
                    $response=array(
                        'result' => 'false',
                        'reason' => '微信接口异常,退款失败！',
                    );
                    $this->getOrderTable()->rollBack();
                    die(json_encode($response));
                }
            }
            //修改订单状态
            $this->getOrderTable()->cancelOrder($order_id);
            $this->getOrderTable()->commit();
            $response=array(
                'result' => 'true',
                'reason' => '订单取消成功,已退款！',
            );
            die(json_encode($response));
        }catch (\Exception $e){
            $this->getOrderTable()->rollBack();
            $response=array(
                'result' => 'false',
                'reason' => '系统异常,处理失败！',
            );
            die(json_encode($response));
        }
    }
    /*
     * 配餐批量发货
     */
    public function batchSendAction()
    {
        $post = $this->request->getPost()->toArray();
        try{
            $this->getOrderTable()->beginTransaction();
            $orderList = array();
            $orderList = $this->getOrderTable()->getOrderListAll($post);
            foreach ($orderList as $order){
                if($order['status'] != '2'){
                    $response=array(
                        'result' => 'false',
                        'reason' => '发货失败，请选择待发货订单！',
                    );
                    die(json_encode($response));
                }
                $this->getOrderTable()->sendOrder($order['order_id'],array());
            }
            
            $this->getOrderTable()->commit();
            $response=array(
                'result' => 'true',
                'reason' => '批量发货成功！',
            );
            die(json_encode($response));
        }catch (\Exception $e){
            $this->getOrderTable()->rollBack();
            $response=array(
                'result' => 'false',
                'reason' => '系统异常，发货失败！',
            );
            die(json_encode($response));
        }
    }

}
